
#include <WProgram.h>


// values returned from getIRKey() for Sony TV remote
#define IR_ONE   128
#define IR_TWO   129
#define IR_THREE 130
#define IR_FOUR  131
#define IR_FIVE  132
#define IR_SIX   133
#define IR_SEVEN 134
#define IR_EIGHT 135
#define IR_NINE  136
#define IR_ZERO  137
#define IR_ENTER 139
#define IR_CHUP  144
#define IR_CHDN  145
#define IR_VOLUP 146
#define IR_VOLDN 147
#define IR_MUTE  148
#define IR_POWER 149
#define IR_RECALL 187

#define IR_FF    216
#define IR_RW    217
#define IR_RECORD 218
#define IR_PIP   219
#define IR_PAUSE 220
#define IR_STOP  222
#define IR_PLAY  223
#define IR_MENU  224
#define IR_OK    229



//
int getIRKey( int irPin, int timeout ) {
  int start_bit = 2200;       // Start bit threshold (Microseconds)
  int bin_1 = 1000;           // Binary 1 threshold (Microseconds)
  int bin_0 = 400;            // Binary 0 threshold (Microseconds)
  int data[12];
  int seed = 1;
  int i;

  int gotIt=0;
  for( i=0; i<15; i++ ) { // try a few times to get start pulse
    long val = pulseIn( irPin, LOW, 1000); 
    if( val > start_bit ) {
      gotIt = 1;
      break;
    }
  }
  if( !gotIt ) return -1;  // oh well

  // Start measuring bits, want low pulses
  for( i=0; i<11; i++ ) { 
    data[i] = pulseIn( irPin, LOW );
  }

  //if(debug == 1) 
  //  Serial.println("-----");

  for( i=0; i<11; i++) {         //Parse them
    // if (debug == 1) 
    //  Serial.println(data[i]);
    if(data[i] > bin_1)         // is it a 1?
      data[i] = 1;
    else if(data[i] > bin_0)    // is it a 0?
      data[i] = 0;
    else 
      data[i] = 2;              // Flag as invalid 
  }

  for( i=0; i<11; i++) {       // Pre-check data for errors
    if(data[i] > 1) 
      return -1;                // Return -1 on invalid data
  }

  int result = 0;  // FIXME: this could be better perhaps
  for( i=0; i<11; i++) {        // Convert bits to integer
    if(data[i] == 1) {
      result += seed;
    }
    seed = seed * 2;
  }
  return result;                 // Return key number
}
